<template>
  <div>
    <!-- 附件管理 -->
    <el-dialog title="附件管理" :visible.sync="visible" :close-on-click-modal="false" style="margin-top: 100px"
               width="700px"
               top="5vh" append-to-body>
      <div class="img-list">
        <div class="img-li-box" v-for="(item,key) in fileList" :key="key">
          <img class="img-li-b--url" :src="getFileSuffix(item)">
          <div class="img-li-b--bottom">
            <div class="img-li-b--name">{{ item.fileName }}</div>
          </div>

          <!-- 删除icon -->
          <div class="img-li-b--delete">
            <i @click="handleFileRemove(item.fileName, item.fileId)" class="el-icon-delete" v-if="isEdit"></i>
          </div>

          <!-- 放大icon -->
          <div class="img-li-b--layer" v-if="item.isImg == 'Y'" @click="handleFileEnlarge(item.fileId, item.filePath)">
            <i class="el-icon-view"></i>
          </div>

          <!-- 下载 -->
          <div class="img-li-b--layer" v-if="item.isImg == 'N'" @click="handleFileDownload(item.fileId)">
            <i class="el-icon-download"></i>
          </div>
        </div>

        <!-- 上传进度 -->
        <div v-if="!pass && progress !== 0" class="img-li-box img-li-b--progress">
          <el-progress type="circle" :percentage="progress" :status="proStatus"></el-progress>
        </div>

        <!-- 上传按钮 -->
        <div class="img-li-b--upload">
          <el-upload class="img-li-b--upl--field"
                     :key="uuid"
                     accept=".txt,.pdf,.doc,.docx,.xls,.xlsx,.jpg,.png,.jpeg"
                     ref="upload"
                     :multiple="true"
                     list-type="picture-card"
                     :limit="limit"
                     :show-file-list="false"
                     :action="uploadAnnexUrl"
                     :headers="headers"
                     :data="{uuid: uuid, annexType: annexType, masterId: masterId, type: type}"
                     :on-change="handleOnChange"
                     :before-upload="handleBeforeUpload"
                     :on-exceed="handleExceed"
                     :on-success="handleOnSuccess"
                     :on-error="handleOnError"
                     :on-progress="handleOnProgress" v-if="this.uploadShow && this.isEdit">
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>

      </div>

    </el-dialog>

    <!-- 放大弹窗 -->
    <el-dialog title="图片预览"
               :visible.sync="isEnlargeImage"
               :modal-append-to-body="false"
               width="60%">

      <el-button type="primary" size="small" @click="handleImageFileDownload">下载图片</el-button>
      <img @click="isEnlargeImage = false" style="width:100%; height: 100%;" :src="enlargeImage">

    </el-dialog>

  </div>

</template>

<script>
  import {getToken} from "@/utils/auth";
  import {getAnnexList, deleteAnnexFile} from "@/api/engineering/annex";
  import doc from "@/assets/file/doc.png";
  import xls from "@/assets/file/xls.png";
  import jpg from "@/assets/file/njgp.png";
  import txt from "@/assets/file/txt.png";
  import pdf from "@/assets/file/pdf.png";

  export default {
    name: 'annex-upload-list',
    props: {
      // 文件数量限制
      limit: {
        type: Number,
        default: 10,
      },
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 10,
      }
    },
    data() {
      return {
        // 主表ID
        masterId: 0,
        // 是否可以编辑
        isEdit: true,
        // 附件类型
        annexType: 1,
        // uuid
        uuid: null,
        // 类型 0 合同 1 变更 2 其他
        type: 0,
        // 附件数量
        annexCount: 0,
        // 上传按钮是否显示
        uploadShow: true,
        // 遮罩层
        visible: false,
        // 文件ID
        fileId: null,
        baseUrl: process.env.VUE_APP_BASE_API,
        uploadAnnexUrl: process.env.VUE_APP_BASE_API + "/engineering/meterage/detail/upload",
        headers: {
          token: "Bearer " + getToken(),
        },
        // 文件集合
        fileList: [],
        doc: doc,
        xls: xls,
        jpg: jpg,
        txt: txt,
        pdf: pdf,
        //上传进度
        progress: 0,
        //是否上传成功
        pass: null,
        //放大图片
        isEnlargeImage: false,
        //放大图片地址
        enlargeImage: '',
      }
    },
    computed: {
      proStatus() { //上传状态
        if (this.pass) {
          return 'success'
        } else if (this.pass === false) {
          return 'exception'
        } else {
          return 'warning'
        }
      }
    },
    // 方法
    methods: {
      // 显示弹框
      show(uuid, masterId, isEdit, type) {
        this.fileList = [];
        this.uuid = uuid;
        this.masterId = masterId;
        this.isEdit = isEdit;
        this.type = type;
        this.getAnnexList(false);
        // 延迟显示，先数据刷新出来
        setTimeout(() =>{
          this.visible = true;
        },300);
      },
      // 获取附件列表
      getAnnexList(refresh) {
        getAnnexList({uuid: this.uuid, annexType: this.annexType}).then(response => {
          this.fileList = response.list;
          this.annexCount = response.annexCount;
          if (this.annexCount >= this.limit) {
            this.uploadShow = false;
          } else {
            this.uploadShow = true;
          }
          if (refresh) {
            this.$parent.choiceList();
          }
        });
      },
      // 获取文件后缀
      getFileSuffix(file) {
        let suffix = file.fileName.substring(file.fileName.lastIndexOf(".") + 1)
        if (file.isImg == 'Y') {
          return process.env.VUE_APP_BASE_API + file.filePath;
        } else {
          if (suffix == "txt") {
            return this.txt;
          } else if (suffix == "pdf") {
            return this.pdf;
          } else if (suffix == "doc" || suffix == "docx") {
            return this.doc;
          } else if (suffix == "xls" || suffix == "xlsx") {
            return this.xls;
          } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
            return this.jpg;
          }
        }
      },
      // 上传前loading加载
      handleBeforeUpload(file) {
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
      },
      // 文件个数超出
      handleExceed() {
        this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
      },
      // 上传进度
      handleOnProgress(e, file) { //开始上传
        this.progress = Math.floor(e.percent)
      },
      // 发生变化
      handleOnChange(file) {
        if (file.status == 'ready') {
          this.pass = null;
          this.progress = 0;
        } else if (file.status == 'fail') {
          this.$message.error("文件上传出错，请刷新重试！")
        }
      },
      // 上传成功
      handleOnSuccess(response, file) {
        this.pass = true;
        this.$message.success("上传成功");
        let result = response.data;
        let flag = false;
        if (result == 1) {
          flag = true;
        }
        this.getAnnexList(flag);
      },
      // 上传失败
      handleOnError(e, file) {
        this.pass = false;
      },
      // 删除文件
      handleFileRemove(fileName, fileId) {
        this.$modal.confirm('确认删除文件[' + fileName + ']？').then(() =>  {
          return deleteAnnexFile({fileId: fileId, masterId: this.masterId});
        }).then((response) => {
          let result = response.data;
          let flag = false;
          if (result == 1) {
            flag = true;
          }
          this.getAnnexList(flag);
          this.$message.success("删除成功");
        }).catch(() => {
        });
      },
      // 下载文件
      handleFileDownload(fileId) {
        this.$download.meterageAnnex(fileId, this.masterId);
      },
      // 放大图片
      handleFileEnlarge(fileId, _url) {
        this.fileId = fileId;
        if (_url) {
          this.enlargeImage = process.env.VUE_APP_BASE_API + _url;
          this.isEnlargeImage = !this.isEnlargeImage;
        }
      },
      // 预览图片对话框下载文件
      handleImageFileDownload() {
        this.$download.meterageAnnex(this.fileId, this.masterId);
      }
    }
  }
</script>

<style lang="scss">
  .img-list {
    overflow: hidden;
    width: 100%;

    // 文件列表
    .img-li-box {
      float: left;
      text-align: left;
      position: relative;
      display: inline-block;
      width: 200px;
      height: 270px;
      padding: 5px;
      margin: 5px 20px 20px 0;
      border: 1px solid #d1dbe5;
      border-radius: 4px;
      transition: all .3s;
      box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .12), 0 0 6px 0 rgba(0, 0, 0, .04);

      // 图片
      .img-li-b--url {
        display: block;
        width: 100%;
        height: 190px;
        margin: 0 auto;
        border-radius: 4px;
      }

      // 底部
      .img-li-b--bottom {
        margin-top: 10px;

        // 名称
        .img-li-b--name {
          width: 90%;
          text-overflow: ellipsis;
          overflow: hidden;
          height: 25px;
          line-height: 25px;
        }
      }

      // 删除按钮
      .img-li-b--delete {
        position: absolute;
        bottom: 10px;
        right: 10px;
        color: #8492a6;
        cursor: pointer;
        font-size: 1.1em;
      }

      // 放大遮罩层
      .img-li-b--layer {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        height: 200px;
        color: #fff;
        text-align: center;
        z-index: 5;
        background-color: rgba(0, 0, 0, .4);

        // 放大按钮
        i {
          font-size: 1.6em;
          margin-top: 80px;
        }
      }

      .img-li-b--delete,
      .img-li-b--layer {
        opacity: 0;
        transition: all .3s;
      }

      // 悬浮可见删除 or 放大按钮
      &:hover {

        .img-li-b--delete,
        .img-li-b--layer {
          opacity: 1;
        }
      }

      // 上传进度
      &.img-li-b--progress {
        text-align: center;
        padding-top: 50px;
      }

    }

    // 上传按钮
    .img-li-b--upload {
      float: left;
      width: 200px;
      height: 270px;
      display: table;
      text-align: center;

      .img-li-b--upl--field {
        width: 100%;
        display: table-cell;
        vertical-align: middle;
      }
    }
  }
</style>
